import java.sql.*;
import java.io.*;
import oracle.jdbc.pool.OracleDataSource;

public class dbapi{

	public static Connection conn;
	public static boolean connected;
	public static String msg;
	private static String server;
	private static String port;
	private static String user;
	private static String pass;
	private static String db;
	public static void dbapi()
	{
		connected = false;
		server = "localhost";
		port = "1521";
		user = "project";
		pass = "project";
		db = "orcl";
	}
	public static boolean connect()
	{
		OracleDataSource ods;
		try {
			ods = new OracleDataSource();
			ods.setURL("jdbc:oracle:thin:project/project@localhost:1521:orcl");
		    conn = ods.getConnection();
		} catch (SQLException e) {
			msg = stack2string(e);
			connected = false;
			return false;
		}
		connected = true;
		return true;
	}
	public int getHomeCount()
	{
		int count = -1;
		try
		{
			Statement stmt = conn.createStatement();
			ResultSet rset = stmt.executeQuery("select count(*) from homes");
			rset.next();
			count = rset.getInt(1);
			stmt.close();
		}catch(SQLException e){
			msg = stack2string(e);
		}
	
		return count;
	}
	public static boolean newHome(int floorSpace, int floors, int bedrooms, 
			int bathrooms,int landSize, int year, int agentID)
	{
		try{
			Statement stmt = conn.createStatement();
			stmt.executeQuery(
				"insert into homes vales (HomeID.NEXTVAL," +
				floorSpace + "," + floors + "," + bedrooms +
				"," + bathrooms + "," + landSize + "," + year +
				"," + agentID);
			stmt.close();
		}catch(SQLException e){
			msg = stack2string(e);
			return false;
		}
		return true;
	}
	
	public static boolean delHome(int homeID)
	{
		try{
			Statement stmt = conn.createStatement();
			stmt.execute("delete from homes where homeID = " + homeID);
			stmt.close();
		}catch(SQLExeption e){
			msg = stack2string(e);
			return false;
		}
		return true;
	}	
	public static String stack2string(Exception e) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return "------\r\n" + sw.toString() + "------\r\n";
  		}
  		catch(Exception e2) {
    			return "bad stack2string";
  		}
 	}	
}
